/*!
 * Page: mall/pay/Pay
 * License: MIT
 * Created: 2019-08-27 10:46
 */

// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
import getMessage from 'ts-msg-handler'
import { mallApi } from '/api/mall'
import { getDomoUser } from '/store/actions'
import { getAppId, getServer, onNews } from '/store/mutations'
import { GlobalData } from '/store/state'
import { $event } from '/utils'

Page({
  data: {
    commodityId: '',
    orig: true,
    top: GlobalData.menuRect.top,
    height: GlobalData.menuRect.height,
    currencyName: GlobalData.currencyName,
    // 收货地址
    realname: '手机号码：',
    phone: '13666666666',
    province: '湖南',
    city: '长沙',
    country: 'AAA区',
    detail: 'aa',
    info: {} as DomoCommodity,
    /** 商品数量 */
    count: 1,
    /** 选择的规格(旧,已废弃) */
    options: '',
    /** 总价(单位:元) */
    countPrice: 0,
    /** 总价(单位:分) */
    countPrices: 0,
    /** 积分 */
    score: 0,
    /** 积分兑换人民币比例 */
    exchangeRate: 0.1,
    reMarks: '',
    /** 用户的积分 */
    userScore: 0,
    /** 购买商品所需积分 */
    needScore: 0,
    /** 当前用户购买单商品需要的价格(主要用于计算VIP价格) */
    userPrice: 0,
    payToast: false,
    paySuccess: true,
    /** 选择的规格(新,带库存和差价) */
    sku: {} as any,
    /** 计算差价后的原价 */
    price: 0,
    /** 计算差价后的积分 */
    infoScore: 0,
    /** 差价 */
    extraPrice: 0,
  },
  async onLoad(options: any) {
    if (GlobalData.phone != '') {
      this.setData({
        phone: GlobalData.phone,
      })
    }
    const info = await mallApi.getCommodityDetail(options.commodityId)
    console.log(info.price)
    const buy_count = parseInt(options.count)
    this.setData({
      commodityId: options.commodityId,
      orig: options.orig === '1' ? true : false,
      info,
      price: info.price,
      total_price: options.total_price,
      options: info.options ? info.options[0] : '',
      count: buy_count,
      sku: info.sku ? info.sku[0] : {},
    })
    const form = wx.getStorageSync('address')
    this.setData(form)
    this.getPrice()
  },
  onShow() {
    $event.on('after:boot', this, () => {
      this.getPosition()
    })
    getDomoUser()
    this.getPosition()
  },
  getPosition() {
    this.setData({
      access: GlobalData.access,
      exchangeRate: GlobalData.currency.settings['recharge-ratio'],
      currencyName: GlobalData.currencyName,
      top: GlobalData.menuRect.top,
      height: GlobalData.menuRect.height,
    })
  },
  chooseAddress() {
    const chooseAddress = () => {
      wx.chooseAddress({
        success: (res) => {
          const form = {
            realname: res.userName,
            phone: res.telNumber,
            province: res.provinceName,
            city: res.cityName,
            country: res.countyName,
            detail: res.detailInfo,
          }
          wx.setStorageSync('address', form)

          this.setData(form)
        },
      })
    }

    // 获取收货地址授权信息
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.address'] === false) {
          wx.openSetting({
            success: (res) => {
              if (res.authSetting['scope.address'] === false) {
                wx.showToast({ title: '请允许使用您的收货地址', icon: 'none' })
              } else {
                chooseAddress()
              }
            },
          })
          return
        }
      },
    })
    chooseAddress()
  },
  chooseOptions(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { item },
      },
    } = e
    this.setData({
      sku: item,
      options: item.name,
    })
    this.getPrice()
  },
  onInput(e: WechatMiniprogram.CustomEvent) {
    this.setData({
      reMarks: e.detail.value,
    })
  },
  reduce() {
    if (this.data.count < 2) return
    this.setData({
      count: this.data.count - 1,
    })
    this.getPrice()
  },
  add() {
    if (this.data.count < 5) {
      this.setData({
        count: this.data.count + 1,
      })
      this.getPrice()
    } else {
      wx.showToast({ title: '单次购买最多5张门票！', icon: 'none' })
    }
  },
  getFormatPrice(num: any, digit = 2) {
    const priceCount = (+num / 100).toFixed(digit)
    let price
    if (+priceCount > 0) {
      if (+priceCount.split('.')[1] > 0) {
        price =
          +priceCount.charAt(priceCount.length - 1) > 0
            ? priceCount
            : priceCount.slice(0, priceCount.length - 1)
      } else {
        price = priceCount.split('.')[0]
      }
    } else {
      price = '0'
    }
    console.log('format price')
    return price
  },
  /** 计算金额 */
  getPrice() {
    const {
      data: { sku, info },
    } = this
    let extraPrice = 0,
      countPrice = 0,
      price = 0,
      countPrices = 0,
      userPrice = 0,
      needScore = 0
    if (sku && sku.extra) {
      extraPrice = +sku.extra + extraPrice
    }
    price = this.data.price
    countPrice = price * this.data.count
    countPrices = price * this.data.count * 100
    const user = wx.getStorageSync(`${getServer()}/logged`).data || []
    const userScore = 0
    userPrice = info.price
    const score = 0
    this.setData({
      countPrice,
      countPrices,
      score,
      userScore,
      needScore,
      userPrice,
      user,
      price: this.data.price,
      infoScore: info.score + extraPrice,
      extraPrice,
    })
  },
  openConfirm() {
    if (!this.data.phone) {
      wx.showToast({ title: '请选择收货地址！！', icon: 'none' })
      // return
    }
    if (
      this.data.info.remote_areas &&
      this.data.info.remote_areas.includes(this.data.province.slice(0, 2))
    ) {
      // wx.showToast({ title: '抱歉，偏远地区暂不发货，感谢理解', icon: 'none' })
      // return
    }
    if (this.data.info.buying_read) {
      this.setData({ showConfirm: true })
    } else {
      this.onSubmit()
    }
  },
  async onSubmit() {
    try {
      await onNews(['{{MERCHANT_SHIPPING_KEY}}'])
    } catch (error) {
      // wx.showToast({ title: '请配置正确的订阅消息key，具体位置在package.json', icon: 'none' })
    }
    this.closeConfirm()
    this.setData({ submitLock: true })
    try {
      const payInfo = await mallApi.postMallOrder({
        commodity_id: this.data.commodityId,
        commodity_option: this.data.options,
        is_orig_price: 1,
        user_remark: '',
        pay_score: 0,
        address: {
          name: this.data.realname,
          phone: this.data.phone,
          province: this.data.province,
          city: this.data.city,
          country: this.data.country,
          detail: this.data.detail,
        },
        openid: wx.getStorageSync(`${getServer()}/openId`).data,
        appid: getAppId() ? getAppId() : '{{APP_ID}}',
        quantity: this.data.count,
      })
      if (payInfo.pay_amount === 0) {
        this.payShowToast(true)
        return
      }
      wx.requestPayment({
        ...payInfo.pay_data,
        success: () => {
          this.payShowToast(true)
        },
        fail: () => {
          this.payShowToast(false)
        },
      })
    } catch (error) {
      wx.showToast({
        title: `${getMessage(error.data).getMessage()}`,
        icon: 'none',
      })
    }
  },
  closeConfirm() {
    this.setData({ showConfirm: false })
  },
  payShowToast(success: boolean) {
    this.setData({
      payToast: true,
      paySuccess: success,
    })
  },
  closePayShow() {
    this.setData({ payToast: false })
  },
  toHome() {
    wx.switchTab({
      url: '/pages/feed/list/list',
    })
  },
  toOrder() {
    wx.navigateTo({
      url: '/mall/order/order',
    })
    this.setData({ payToast: false })
  },
})
